﻿using UnityEngine;
using System.Collections;

public class ThirdPersonPlayerAnimation : MonoBehaviour
{
    public float runSpeedScale = 1.0f;
    public float walkSpeedScale = 1.0f;

    private PlatformCharacterController platformCharController;
    private PhysicsCharacterMotor phsxMotor;

    void Start()
    {
        animation.wrapMode = WrapMode.Loop;

        animation["run"].layer = -1;
        animation["walk"].layer = -1;
        animation["idle"].layer = -2;
        animation.SyncLayer(-1);

        animation["jump"].layer = 10;
        animation["jump"].wrapMode = WrapMode.ClampForever;

        animation["fall"].layer = 10;
        animation["fall"].wrapMode = WrapMode.Loop;

        animation["land"].layer = 10;
        animation["land"].wrapMode = WrapMode.Once;

        animation.Stop();
        animation.Play("idle");

        platformCharController = GetComponent<PlatformCharacterController>();
        phsxMotor = GetComponent<PhysicsCharacterMotor>();

    }

    void Update()
    {
        // float currentSpeed = rigidbody.velocity.magnitude;

        if (phsxMotor.grounded)
        {
            animation.Blend("fall", 0.0f, 0.3f);
            animation.Blend("jump", 0.0f, 0.3f);

            if (rigidbody.velocity.magnitude > phsxMotor.maxForwardSpeed - 1)
            {
                animation.CrossFade("run");

                animation.Blend("walk", 0.0f, 0.3f);
            }

            else if (rigidbody.velocity.magnitude > (phsxMotor.maxForwardSpeed * platformCharController.walkMultiplier - 1))
            {
                animation.CrossFade("walk");

                animation.Blend("run", 0.0f, 0.3f);
            }

            else
            {
                animation.Blend("walk", 0.0f, 0.3f);
                animation.Blend("run", 0.0f, 0.3f);
            }

            animation["run"].normalizedSpeed = runSpeedScale;
            animation["walk"].normalizedSpeed = walkSpeedScale;
        }

        if (phsxMotor.jumping)
        {
            if (!phsxMotor.jumpingReachedApex && phsxMotor.jumping)
            {
                animation.CrossFade("jump", 0.2f);
                animation.Blend("fall", 0.0f, 0.3f);
            }

            else
            {
                animation.Blend("jump", 0.0f, 0.3f);
                animation.CrossFade("fall", 0.2f);
            }

            animation.Blend("walk", 0.0f, 0.1f);
            animation.Blend("run", 0.0f, 0.1f);
        }
    }

    public void DidLand()
    {
        animation.Play("land");
    }
}